﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using BlogEngine.Core;
using System.Collections.Generic;
using BlogEngine.Core.Web.Controls;
using System.Collections.Specialized;
using System.IO;
using System.Xml;

public partial class themes_arthemia_PostViewFrontPage : BlogEngine.Core.Web.Controls.PostViewBase
{
    private StringDictionary settings;

    protected void Page_Load(object sender, EventArgs e)
    {
        settings = GetThemeSettings();


        List<Post> tmp = BlogEngine.Core.Post.GetPostsByCategory(new Guid(settings["HeadlineCategory"]));
        if(tmp.Count>0)
            this.Post = tmp[0];

        BindCategories();

        if (Page.User.Identity.IsAuthenticated)
            BindFormElements();

        //Guid categoryId = new Guid(Request.QueryString["id"]);
        List<IPublishable> Posts = BlogEngine.Core.Post.GetPostsByCategory(new Guid(settings["FeaturedCategory"])).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));

        string query = Request.QueryString["theme"];
        string theme = !string.IsNullOrEmpty(query) ? query : BlogSettings.Instance.Theme;
        string path = string.Concat(Utils.RelativeWebRoot, "themes/", theme, "/PostViewLeft.ascx");
        //Control.MapPath() 

        foreach (Post usePost in Posts)
        {
            PostViewBase postView = (BlogEngine.Core.Web.Controls.PostViewBase)LoadControl(path);
            postView.ShowExcerpt = BlogSettings.Instance.ShowDescriptionInPostList;
            postView.Post = usePost;
            postView.ID = usePost.Id.ToString().Replace("-", string.Empty);
            postView.Location = ServingLocation.PostList;
            leftcontent.Controls.Add(postView);
        }
    }

    private void BindFormElements()
    {
        foreach (Category cat in Category.Categories)
        {
            if(HasPosts(cat))
            {
                DdlFeatured.Items.Add(new ListItem(Server.HtmlEncode(cat.Title), cat.Id.ToString()));
                if(cat.Id.ToString()==settings["FeaturedCategory"])
                    DdlFeatured.SelectedValue = settings["FeaturedCategory"];
                DdlHeadline.Items.Add(new ListItem(Server.HtmlEncode(cat.Title), cat.Id.ToString()));
                if (cat.Id.ToString() == settings["HeadlineCategory"])
                    DdlHeadline.SelectedValue = settings["HeadlineCategory"];
            }
        }
    }

    private void BindCategories()
    {
        int iCount = 0;
        foreach (Category  item in Category.Categories)
        {
            if (!item.Description.StartsWith(":"))
            {
                iCount++;
                HtmlGenericControl div = new HtmlGenericControl("div");
                div.Attributes.Add("class", string.Concat("category cat-", iCount));
                div.ID = string.Concat("cat-", iCount);

                HtmlGenericControl span = new HtmlGenericControl("span");
                span.Attributes.Add("class", "cat_title");

                string uri = Utils.RelativeWebRoot + "category/" + Utils.RemoveIllegalCharacters(item.CompleteTitle()) + BlogSettings.Instance.FileExtension;
                HtmlAnchor anc = new HtmlAnchor();
                anc.HRef = uri;
                anc.InnerHtml = HttpUtility.HtmlEncode(item.CompleteTitle());

                span.Controls.Add(anc);

                HtmlAnchor anc2 = new HtmlAnchor();
                anc2.HRef = uri;
                anc2.InnerHtml = HttpUtility.HtmlEncode(item.Description);

                div.Controls.Add(span);
                div.Controls.Add(anc2);


                phCategoryList.Controls.Add(div);
            }
        }        
    }

    public string getImage(bool ShowExcerpt, string input)
    {

        if (!ShowExcerpt || input == null)
            return "";
        
        string pain = input;
        string pattern = @"<img(.|\n)+?>";
        
        System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, pattern,

        System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);

        if (m.Success)
        {
            string src = getSrc(m.Value);
            string img = string.Format("<img width='300' class='left'  {0}  />", src);
            return img;
        }
        else
        {
            return "";
        }
    }



    string getSrc(string input)
    {
        string pattern = "src=[\'|\"](.+?)[\'|\"]";

        System.Text.RegularExpressions.Regex reImg = new System.Text.RegularExpressions.Regex(pattern,
        System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);

        System.Text.RegularExpressions.Match mImg = reImg.Match(input);

        if (mImg.Success)
        {
            return mImg.Value;
        }

        return "";
    }


    protected void BtnSave_Click(object sender, EventArgs e)
    {
        settings["HeadlineCategory"] = (DdlHeadline.SelectedValue);
        settings["FeaturedCategory"] = (DdlFeatured.SelectedValue);
        

        SaveSettings();
        //ApplyThemeSettings();
    }

    private StringDictionary GetThemeSettings()
    {
        StringDictionary temp;
        string dataSource = System.Web.HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation) + "arthemia.xml";

        // Read them in
        if (!File.Exists(dataSource))
        {
            // No file... Load default settings.
            temp = new StringDictionary();

            int i = 0;
            foreach (Category item in Category.Categories )
            {
                
                if(HasPosts(item))
                    break;
                i++;
            }
            temp.Add("HeadlineCategory", Category.Categories[i].Id.ToString());
            temp.Add("FeaturedCategory", Category.Categories[i].Id.ToString());
        }
        else
        {
            // Check if it is in the cache already
            temp = (StringDictionary)Cache["arthemia"];

            if (settings == null)
            {
                temp = new StringDictionary();
                LoadSettings(dataSource, temp);
                Cache.Insert("arthemia", temp, new System.Web.Caching.CacheDependency(dataSource));
            }
        }
        return temp;
    }

    private void LoadSettings(string dataSource, StringDictionary settings)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(dataSource);

        foreach (XmlNode themeNode in doc.SelectSingleNode("Theme").ChildNodes)
        {
            string name = themeNode.Name;
            string value = themeNode.InnerText;

            settings.Add(name, value);
        }
    }

    private void SaveSettings()
    {
        string dataSource = System.Web.HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation) + "arthemia.xml";
        using (XmlTextWriter writer = new XmlTextWriter(dataSource, System.Text.Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 4;
            writer.WriteStartDocument(true);
            writer.WriteStartElement("Theme");

            foreach (string key in settings.Keys)
            {
                writer.WriteElementString(key, settings[key]);
            }

            writer.WriteEndElement();
        }
    }

    private bool HasPosts(Category cat)
    {
        foreach (Post post in Post.Posts)
        {
            if (post.IsVisible)
            {
                foreach (Category category in post.Categories)
                {
                    if (category == cat)
                        return true;
                }
            }

        }
        return false;
    }

}
